<script setup>
import { ref, reactive, onMounted, defineProps, watch, nextTick, toRaw } from 'vue'
import { getMenuList, updatePermission } from '@/api'

const props = defineProps({
  isShowRoleDialog: Boolean,
  roleItem: Object
})

const emits = defineEmits(['closed']);
const state = reactive({
  menuList: []
})
const tree = ref()

watch(
  () => props.roleItem,
  (role) => {
    if (props.isShowRoleDialog) {
      const { checkedKeys } = role.permissionList;
      nextTick(() => {
        tree.value.setCheckedKeys(checkedKeys);
      })
    }
  }
)

onMounted(() => {
  query();
})

const query = async () => {
  state.menuList = await getMenuList();
}

const handelClosed = () => {
  emits('closed');
}

const submit = async () => {
  const nodes = tree.value.getCheckedNodes();
  const halfCheckedKeys = tree.value.getHalfCheckedKeys();
  let checkedKeys = [];
  let parentKeys = [];
  // console.log('nodes', nodes)
  nodes.map(item => {
    if (!item.children) {
      checkedKeys.push(toRaw(item._id));
    } else {
      parentKeys.push(toRaw(item._id));
    }
  })
  console.log('checkedKeys', checkedKeys)
  console.log('parentKeys', parentKeys)

  let data = {
    _id: props.roleItem._id,
    permissionList: {
      checkedKeys,
      halfCheckedKeys: [
        ...parentKeys,
        ...halfCheckedKeys,
      ],
    }
  }
  await updatePermission(data)
  emits('closed');
}

</script>
<template>
  <el-dialog title="权限设置" :model-value="props.isShowRoleDialog" @closed="handelClosed">
    <el-form label-width="150">
      <el-form-item label="角色名称">
        {{ props.roleItem.roleName }}
      </el-form-item>
      <el-form-item label="权限">
        <el-tree ref="tree" :data="state.menuList" show-checkbox node-key="_id" default-expand-all
          :props="{ children: 'children', label: 'menuName', }" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button  @click="emits('closed')">取消</el-button>
      <el-button @click="submit" type="primary">确定</el-button>
    </template>
  </el-dialog>
</template>